package ernie.server.context;

import java.io.IOException;
import java.util.Map;

import misc.HTMLStringStream;
import stock.avanza.AvanzaScrape;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import ernie.server.ParameterParser;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 12:38:28 AM - Dec 9, 2011
 */
public class ThreadCommandContext implements HttpHandler {

    private final AvanzaScrape avanza;

    public ThreadCommandContext(AvanzaScrape avanza) {
        this.avanza = avanza;
    }

    @Override
    public void handle(HttpExchange he) throws IOException {
        ParameterParser pp = new ParameterParser(he.getRequestURI());
        Map<String, String> args = pp.parseQuery();
        if (args.containsKey("name") && !args.get("name").isEmpty()) {
            String target = args.get("name");
            avanza.getThread(target).setFastUpdate(true);
            try {
                HTMLStringStream hss = new HTMLStringStream(he);
                hss.write("OK, fast updates for " + target + " activated.");
                hss.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        } else {
            try {
                HTMLStringStream hss = new HTMLStringStream(he);
                hss.write("Invalid target");
                hss.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
